package com.aiju.cash.ui.multiple_shops.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.aiju.app.DataProviderManager;
import com.aiju.app.config.ConfigManager;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Shop;
import com.aiju.cash.R;
import com.aiju.cash.core.event.ShopListChangeEven;
import com.aiju.cash.ui.enter.CheckInActivity;
import com.aiju.cash.ui.enter.entity.EnterShopInfo;
import com.aiju.cash.ui.multiple_shops.adapter.ShopManagerAdapter;
import com.aiju.cash.ui.multiple_shops.en.ShopManagerListType;
import com.aiju.cash.ui.multiple_shops.menu.PopuMenu;
import com.aiju.cash.ui.multiple_shops.present.ipresent.IShopManagerPresent;
import com.aiju.cash.ui.multiple_shops.present.presentiml.ShopManagerPresent;
import com.aiju.cash.ui.multiple_shops.widget.MenuLinearLayout;
import com.aiju.cash.ui.multiple_shops.widget.MenuPopuWindow;
import com.aiju.cash.util.GsonHelper;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;
import com.aiju.support.recyclerView.DividerItemDecoration;
import com.aiju.utils.PreferencesUtils;
import com.aiju.utils.T;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;

import java.util.ArrayList;
import java.util.List;


/**
 * 门店管理或者 门店切换
 *
 * @author 流冥
 * @date 2017-06-12
 */
public class ShopManagerActivity extends BaseTitleActivity implements ShopManagerAdapter.OnRecyclerViewListener, IShopManagerUiListener {

    List<Shop> list = new ArrayList<>();
    ShopManagerAdapter adapter;
    private RecyclerAdapterWithHF mAdapter;
    private int currentNum = 1;
    private int pageSize = 10;
    ImageView imageView;
    private MenuPopuWindow menuPopuWindow;
    private RecyclerView recyclerviewTeams;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private SwipeRefreshHelper mSwipeRefreshHelper;
    private boolean isLoad;
    private boolean isRefresh = true;
    private IShopManagerPresent iShopManagerPresent;
    private ShopManagerListType t;//属于哪种情况：切换店铺，管理店铺
    public static final String DATA = "data";
    public static final String FROM = "from";
    private ShopManagerListType from;//默认切换店铺


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_manager);
        getData();
        initView();
        rquestShopList();

        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(ShopListChangeEven event) {
                list.clear();
                rquestShopList();
            }
        });
    }

    void getData() {
        if (getIntent() != null) {
            ShopManagerListType serializableExtra = (ShopManagerListType) getIntent().getSerializableExtra(FROM);
            if (serializableExtra != null) {
                from = serializableExtra;
            }
        }
    }

    void initView() {
        initTitle();
        initOther();
        initPresent();
        initListener();

    }

    /**
     * 初始化title
     */
    void initTitle() {

        switch (from) {
            case SHOPMANAGER:
                setCenterTitle("门店管理");
                imageView = new ImageView(this);
                imageView.setImageResource(R.mipmap.icon_shop_managet_add);
                mAiJuTitleBarView.setCustomizedRightView(imageView);
                mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //  显示 popuwindow
                        showPopuMenu();
                    }
                });
                break;
            case CHANGESHOP:
                setCenterTitle("切换门店");
                break;
        }

    }

    void initOther() {
        recyclerviewTeams = (RecyclerView) findViewById(R.id.recyclerview_member);
        recyclerviewTeams.setLayoutManager(new LinearLayoutManager(this));
        recyclerviewTeams.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.sryt_swipe_listview);
        mSwipeRefreshLayout.setEnabled(false);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.app_title_color));
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSwipeRefreshLayout);
        //适配器
        adapter = new ShopManagerAdapter(this, list, from, mUser);
        adapter.setOnRecyclerViewListener(this);
        mAdapter = new RecyclerAdapterWithHF(adapter);
        recyclerviewTeams.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new RecyclerAdapterWithHF.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerAdapterWithHF adapter, RecyclerView.ViewHolder vh, int position) {
                switch (from) {
                    case SHOPMANAGER://店铺管理
                        Shop shop = list.get(position);
                        Intent intent = new Intent(ShopManagerActivity.this, ShopAddOrInfoActivity.class);
                        if (shop.getIsReputationShop().equals("1")) {
                            if (shop.getReviewStatus().equals("3")) {
                                String storeId = ConfigManager.getInstance().getUser().getPhone();
                                String data = PreferencesUtils.getString(DataProviderManager.getContext(), storeId);
                                if (!TextUtils.isEmpty(data)) {
                                    EnterShopInfo shopInfo = GsonHelper.convertEntity(data, EnterShopInfo.class);
                                    Intent intent1 = new Intent(ShopManagerActivity.this, CheckInActivity.class);
                                    intent1.putExtra("enterShopInfo", shopInfo);
                                    startActivity(intent1);
                                    break;
                                }
                            }
                            intent.putExtra("showType", ShopAddOrInfoActivity.SHOW_KOUBEI);
                        } else {
                            intent.putExtra("showType", ShopAddOrInfoActivity.SHOW_COMMON);
                        }
                        intent.putExtra("shop", shop);
                        startActivity(intent);
                        break;
                    case CHANGESHOP://店铺切换
                        if ("2".equals(list.get(position).getShopType())) {
                            T.ToastShort("加盟店不能切换");
                        } else {
                            Intent intentShop = new Intent();
                            intentShop.putExtra("shop", list.get(position));
                            setResult(RESULT_OK, intentShop);
                            finish();
                        }
                        break;
                    default:
                        break;
                }
            }
        });

    }

    void initPresent() {
        iShopManagerPresent = new ShopManagerPresent(this, mDialogHelper);
    }

    void initListener() {
        mSwipeRefreshHelper.setOnSwipeRefreshListener(new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onfresh() {
         /*       L.d("onfresh");
                currentNum = 1;
                isRefresh = true;
                rquestShopList();*/
            }
        });
        mSwipeRefreshHelper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
         /*       if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshHelper.loadMoreComplete(true);
                    return;
                }
                isLoad = true;
                ++currentNum;
                rquestShopList();
                completeRefrsh();*/
            }
        });

    }


    /**
     * 请求数据
     */
    private void rquestShopList() {
        switch (from) {
            case SHOPMANAGER:
                iShopManagerPresent.getShopList(currentNum, pageSize);
                break;
            case CHANGESHOP:
                iShopManagerPresent.getSwitchList(currentNum, pageSize);
                break;
        }
    }


    /**
     * 列表上下拉结束
     */
    private void completeRefrsh() {
        //加载完成
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新完成
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            if (list.size() < pageSize) {
                mSwipeRefreshHelper.setLoadMoreEnable(false);
            } else {
                mSwipeRefreshHelper.setLoadMoreEnable(true);
            }
        }
    }

    @Override
    public void onChangeShop(Shop shopManager) {
        // TODO: 2017/6/12 店铺切换 ----返回app首页，并刷新数据
        Toast.makeText(ShopManagerActivity.this, "调回首页", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onManageShop(Shop shopManager) {
        //   跳转到店铺详情
        Toast.makeText(ShopManagerActivity.this, "店铺详情", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(ShopManagerActivity.this, ShopAddOrInfoActivity.class);
        Bundle b = new Bundle();
        b.putSerializable(DATA, shopManager);
        b.putString("showType", shopManager.getIsReputationShop());
        intent.putExtras(b);
        startActivity(intent);
    }


    @Override
    public void NoDate() {//店铺不会无数据，不用考虑
        if (list.size() != 0) {
            //显示无数据界面,不会无数据
        } else {
            //结束刷新状态
            // completeRefrsh();
        }
    }

    @Override
    public void getShopList(List<Shop> mList) {
//        if (from.equals(SHOPMANAGER)) {
//            addEnterShop(mList);
//        }

        if (isRefresh) {
            list.clear();
        }
        if (adapter == null) {
            adapter.notifyDataSetChanged();
        } else {
            list.addAll(mList);
            adapter.notifyDataSetChanged();
        }
        //completeRefrsh();

    }

    @Override
    public void exception() {
    }


    /**
     * 显示menu popu
     */
    private void showPopuMenu() {
        if (menuPopuWindow == null) {
            menuPopuWindow = new MenuPopuWindow(this, PopuMenu.getMenuList(), new MenuPopuWindow.MenuClickLister() {
                @Override
                public void onClick(int position) {
                    // 跳转界面
                    Intent intent = null;
                    if (position == 1) {//新增普通店铺
                        intent = new Intent(ShopManagerActivity.this, ShopAddActivity.class);
                        intent.putExtra("title", "新增普通门店");
                    } else {
                        intent = new Intent(ShopManagerActivity.this, ShopAddActivity.class);
                        intent.putExtra("title", "新增口碑门店");
                    }
                    startActivity(intent);
                }
            });
        }
        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
        //以某个控件的x和y的偏移量位置开始显示窗口
        menuPopuWindow.showAsDropDown(imageView, -(MenuLinearLayout.dip2px(this, 120)), 0);
        //如果窗口存在，则更新
        menuPopuWindow.update();
    }

    /**
     * 增加口碑开店本地数据
     *
     * @param mList
     */
    private void addEnterShop(List<Shop> mList) {
        String storeId = ConfigManager.getInstance().getUser().getPhone();
        String data = PreferencesUtils.getString(DataProviderManager.getContext(), storeId);
        if (!TextUtils.isEmpty(data)) {
            EnterShopInfo shopInfo = GsonHelper.convertEntity(data, EnterShopInfo.class);
            Shop shop = new Shop();
            shop.setStoreId("");
            shop.setShopName(shopInfo.getMain_shop_name());
            shop.setImageUrl(shopInfo.getMain_image());
            shop.setImageUrl(shopInfo.getMain_image());
            shop.setShopType(shopInfo.getShop_type());
            shop.setReviewStatus(shopInfo.getReview_status());
            shop.setIsReputationShop("1");
            mList.add(shop);
        }
    }
}
